import { BaseContext } from "koa";
import { getRepository } from "typeorm";
import authorize from "../../middleware/authorize";
import { Get, Post, Controller } from "../../middleware/request";
import { Exception } from "../../utils/exception";
import { Product } from "../entity/Product";
import { Category } from "../entity/Category";
import { auth as Auth } from "../../utils/auth";
import { encrypt, decrypt } from "../../utils/crypto";
@Controller("/api/product")
export class CarouselController {
	@Get("/list")
	async getProduct(ctx: BaseContext) {
		try {
			const productRepository = getRepository(Product)
			const categoryRepository = getRepository(Category)
			let productList = await productRepository.find()
			let categoryList = await categoryRepository.find()
			let newList = productList.map(item => {
				return {
					...item,
					category_name: categoryList.find((user) => Number(user.category_id) == Number(item.category_id))?.category_name
				}
			})
			ctx.body = {
				...Exception(200, "查询成功"),
				data: newList,
			}
		} catch (error) {
			console.log(error);

			ctx.body = Exception(112, "查询失败");
		}
	}

	@Post('/detail')
	async detailProduct(ctx: BaseContext) {
		try {
			const { id } = ctx.request.body;
			if (!id) {
				return ctx.body = Exception(112, "id不能为空")
			}
			const productRepository = getRepository(Product)
			const product = await productRepository.findOne(id)
			ctx.body = {
				...Exception(200, "查询成功"),
				data: product
			};
		} catch (error) {
			ctx.body = Exception(112, "删除失败");
		}
	}

	@Post('/addEdit')
	async addEditProduct(ctx: BaseContext) {
		const data = ctx.request.body;
		let name = data.product_id ? '修改' : '添加'
		try {
			const productRepository = getRepository(Product)
			let product = new Product()
			if (data.product_id) {
				product = await productRepository.findOne(data.product_id)
				if (!product) return ctx.body = Exception(112, "标签id不存在");
			} else {
				product = new Product()
			}
			product = data
			await productRepository.save(product);
			ctx.body = Exception(200, `${name}成功`)
		} catch (error) {
			ctx.body = Exception(112, `${name}失败`);
		}
	}



	@Post('/del')
	async delProduct(ctx: BaseContext) {
		try {
			const { id } = ctx.request.body;
			if (!id) {
				return ctx.body = Exception(112, "id不能为空")
			}
			const productRepository = getRepository(Product)
			const product = await productRepository.findOne(id)
			if (!product) return ctx.body = Exception(112, "id不存在");
			await productRepository.remove(product)
			ctx.body = Exception(200, "删除成功");
		} catch (error) {
			ctx.body = Exception(112, "删除失败");
		}
	}
}
